package cn.kent.service.impl;

import cn.kent.config.FileProperties;
import cn.kent.controller.vo.response.FileRes;
import cn.kent.service.FileService;
import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.util.JSONPObject;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author SunChenpeng
 * @date 2021/11/22 17:36
 */
@Service
public class FileServiceImpl implements FileService {
    private final static Logger LOGGER = LoggerFactory.getLogger(FileServiceImpl.class);

    private final FileProperties fileProperties;

    @Autowired
    public FileServiceImpl(FileProperties fileProperties) {
        this.fileProperties = fileProperties;
    }

    @Override
    public FileRes uploadFile(MultipartFile file) throws IOException {
        String fileName = getFileName(file.getOriginalFilename());
        // 文件上传路径
        String uploadPath = fileProperties.getUploadPath();
        File destFile = new File(uploadPath + fileName);
        destFile.getParentFile().mkdirs();
        file.transferTo(destFile);
        FileRes fileRes = new FileRes();
        fileRes.setPath(destFile);
        fileRes.setFileName(fileName);
        fileRes.setUrl(StringUtils.join(fileProperties.getUrlPrefix(), fileName));
        LOGGER.info("上传了文件: " + JSON.toJSONString(fileRes.toString()));
        return fileRes;
    }

    /**
     * 加锁获取唯一文件名
     *
     * @param originalFileName 文件名
     * @return 文件名
     */
    private synchronized String getFileName(String originalFileName) {
        return StringUtils.join(System.currentTimeMillis(), "-", originalFileName);
    }

    @Override
    public List<FileRes> getFileList() {
        List<FileRes> list = new ArrayList<>();

        File baseFile = new File(fileProperties.getUploadPath());
        if (baseFile.isFile() || !baseFile.exists()) {
            return list;
        }

        File[] files = baseFile.listFiles();
        for (File file : files) {
            FileRes fileRes = new FileRes();
            if (file.isDirectory()) {
                fileRes.setFileName(file.getName());
                fileRes.setIsDir(true);
//                if(isAddDirectory){
//                    list.add(file.getAbsolutePath());
//                }
//                list.addAll(getAllFile(file.getAbsolutePath(),isAddDirectory));
                list.add(fileRes);
            } else {
                FileRes fileRes2 = new FileRes();
                fileRes2.setFileName(file.getName());
                fileRes2.setUrl(StringUtils.join(fileProperties.getUrlPrefix(), file.getName()));
                list.add(fileRes2);
            }
        }
        return list;
    }
}
